package phone

import (
	"fmt"
	database "hft/Database"
	"hft/Database/admin"
	utils "hft/Http/Utils"
	"hft/global"
	"hft/tools"
	"time"
)

type CallLog struct{}

func (ca *CallLog) GetCallLog(data *admin.PhoneRecord) error {

	// fmt.Println(tools.JsonParse(data))
	// fmt.Println(data.CallingId)

	fmt.Println(tools.JsonParse(data))

	// 找出分机号
	var dn *admin.DNBroker

	err := global.OC_DB.Where("dn = ?", data.Extension).First(&dn).Error

	if err != nil {
		return err
	}

	// 找出楼盘
	var lou *admin.LouPan

	err = global.OC_DB.Where("name = ? AND region = ?", dn.LouPanName, dn.Region).First(&lou).Error

	if err != nil {
		return err
	}

	data.LouPanId = int(lou.ID)
	data.LouPanName = lou.Name
	data.RegionLink = lou.RegionLink
	data.BelongName = lou.BelongName

	var oldUser *admin.User

	err = global.OC_DB.Where("phone = ?", data.CallingId).First(&oldUser).Error

	if err != nil {

		var city, _ = utils.GetRegionBelongCity(data.RegionLink)
		var clueList []*admin.Clue
		clueList = append(clueList, &admin.Clue{
			Phone:       data.CallingId,
			OriginName:  "400来电",
			PageName:    data.LouPanName,
			LouPanId:    data.LouPanId,
			IP:          data.City,
			Region:      lou.Region,
			BelongName:  data.BelongName,
			PhoneRecord: *data,
		})

		var account *admin.Account

		global.OC_DB.Where("phone = ?", data.CalledId).First(&account)

		var newUser = &admin.User{
			Phone:           data.CallingId,
			RegionLink:      data.RegionLink,
			City:            uint(city),
			Level:           "F",
			Valid:           1,
			UseProductTimes: 1,
			ClueList:        clueList,
			NowBrokerID:     0,
		}

		if data.RecStatus == "1" {
			newUser.NowBrokerID = int(account.ID)
			newUser.BrokerName = account.RealName
			newUser.BrokerTime = time.Now()
			newUser.BrokerNum = 1
		}

		global.OC_DB.Create(&newUser)
	} else {
		var newClue = &admin.Clue{
			Base:        database.Base{UpdateTime: time.Now(), CreateTime: time.Now()},
			UserId:      int(oldUser.ID),
			Phone:       data.CallingId,
			OriginName:  "400来电",
			PageName:    data.LouPanName,
			LouPanId:    data.LouPanId,
			IP:          data.City,
			Region:      lou.Region,
			BelongName:  data.BelongName,
			PhoneRecord: *data,
		}

		global.OC_DB.Create(&newClue)
	}

	return nil

}

var CallLogService = new(CallLog)
